const { goodsOrder, wxRequest } = require('../../api/order')
const { API_OK } = require('../../utils/setting')
const { orderStatus } = require('../../utils/util')
const app = getApp()

Page({
  data: {
    loading: false,
    tabs: [{id: 'all', name: '全部订单'}, {id: 'payment ', name: '待付款'}, {id: 'delivery', name: '待发货'}, {id: 'received', name: '待收货'}, {id: 'comment', name: '待评价'}],
    activeTabIndex: 'all',
    orders: []
  },
  pageData: {
    page: 1,
    canLoadMore: true
  },
  onLoad: function (options) {
    wx.showLoading({ title: '拼命加载中', mask: true })
    this.setData({ loading: true })
    if (wx.getStorageSync('token')) {
      this.getOrder()
    } else {
      app.tokenReadyCallback = this.getOrder
      app.getTokenFailedCallback = () => {
        wx.hideLoading()
        this.setData({ loading: false })
      }
    }
  },
  onPullDownRefresh() {
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.setData({
      loading: true,
      orders: []
    })
    this.getOrder()
  },
  onReachBottom() {
    if (this.data.loading || !this.pageData.canLoadMore) return
    this.setData({ loading: false })
    this.pageData.page += 1
    this.getOrder()
  },
  /**
   * 切换tab
   */
  changeTabIndex({detail: {name}}) {
    this.setData({ activeTabIndex: name, loading: true, orders: [] })
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    Object.keys(wxRequest.queue).forEach(task => {
      wxRequest.queue[task].abort()
    })
    this.getOrder()
  },

  goDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${id}`
    })
  },
  /**
   * 获取订单列表
   */
  async getOrder() {
    try {
      const res = await goodsOrder({
        data: { dataType: this.data.activeTabIndex, page: this.pageData.page },
        callback: () => {
          wx.hideLoading()
          wx.stopPullDownRefresh()
        }
      })
      // console.log(res)
      if (res.code === API_OK) {
        this.pageData.canLoadMore = res.data.current_page < res.data.last_page
        const orderList = res.data.data.map(order => {
          return {
            id: order.order_id,
            orderNumber: order.order_no,
            status: orderStatus(
              order.order_status.value,
              order.pay_status.value,
              order.delivery_status.value,
              order.receipt_status.value,
              order.is_comment
            ),
            summary: order.goods.reduce((summary, item) => {
              return {
                number: summary.number + item.total_num,
                price: summary.price + item.total_num * item.goods_price
              }
            }, {number: 0, price: 0}),
            goods: order.goods.map(item => {
              return {
                id: item.goods_id,
                name: item.goods_name,
                image: item.image && item.image.file_path,
                number: item.total_num,
                specification: item.goods_attr,
                price: item.goods_price
              }
            })
          }
        })
        this.setData({
          loading: false,
          orders: [...this.data.orders, ...orderList]
        })
      }
    } catch(err) {
      console.warn(err)
      this.setData({ loading: false })
    }
  }
})
